<?php
require_once __DIR__ . '/../php_lib/MedooHeadBDB.php';

class Authorization
{
    private $tableName;
    private $time;
    private $columns;

    function __construct($tableName, $columns = [])
    {
        $this->tableName = $tableName;
        $this->time = time();
        $columns[] = 'permission';
        $columns[] = 'acessTime';
        $this->columns = array_unique($columns);
    }
    function checkAuthorization($showError = true, $permissionRequired = null)
    {
        $acessToken = $_SERVER['HTTP_AUTHORIZATION'] ?? null;
        $bdb = (new MedooSqlBDB())->database;
        $selectResult = $bdb->get($this->tableName, $this->columns, ['acessToken' => $acessToken]);
        $msg = '';
        if ($selectResult) {

            if ($this->time - $selectResult['acessTime'] <= 3600) {
                $permission = isset($selectResult['permission']) && $selectResult['permission'] ? json_decode($selectResult['permission'], true) : [];

                $permission_ok = true;
                $permissionName = '';

                //  var_dump($permission);
                //  var_dump($permissionRequired);

                if ($permissionRequired) {
                    foreach ($permissionRequired as $item) {
                        if (!isset($permission[$item]) || !$permission[$item]) {
                            $permission_ok = false;
                            $permissionName = $item;
                            break;
                        }
                    }
                }

                if ($permission_ok) {
                    return array('status' => 1, 'selectResult' => $selectResult);
                } else {
                    if ($showError) {
                        header('HTTP/1.1 402 Permission Required');
                        header("status: 402 Permission Required");
                    }
                    return ['status' => -2, 'msg' => '需要Permission:' . $permissionName];
                }
            } else {
                $msg = 'acessToken过期';
            }
        } else {
            $msg = 'acessToken不正确';
        }
        if ($showError) {
            header('HTTP/1.1 401 Unauthorized');
            header("status: 401 Unauthorized");
        }
        return ['status' => -1, 'msg' => $msg];
    }
}
